package com.leviassaf.al_app_one;

import com.facebook.FacebookException;
import com.facebook.widget.FriendPickerFragment;
import com.facebook.widget.PickerFragment;
import com.facebook.widget.PickerFragment.OnDoneButtonClickedListener;
import com.facebook.widget.PickerFragment.OnErrorListener;
import com.facebook.widget.PlacePickerFragment;

import android.support.v4.app.FragmentManager;
import android.animation.ArgbEvaluator;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;

public class PickerActivity extends FragmentActivity implements
		OnErrorListener, OnDoneButtonClickedListener {

	public static final Uri FRIEND_PICKER = Uri.parse("picker://friend");
	public static final Uri PLACE_PICKER = Uri.parse("picker://place");
	private static final int SEARCH_RADIUS_METERS = 1000;
	private static final int SEARCH_RESULTS_LIMIT = 50;
	private static final String SEARCH_TEXT = "restaurant";
	private static final int LOCATION_CHANGE_THRESHOLD = 50;

	private FriendPickerFragment friendPickerFragment;
	private PlacePickerFragment placePickerFragment;
	private LocationListener locationListener;

	private static final Location LOCATION_HERZLIYA = new Location("") {
		{
			setLatitude(20.9784);
			setLongitude(23.5476);
		}
	};

	@Override
	protected void onCreate(Bundle savedInstance) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstance);
		setContentView(R.layout.pickers);

		Bundle bundleArgs = getIntent().getExtras();
		FragmentManager fragmentManager = getSupportFragmentManager();
		Fragment fragmentToShow = null;
		Uri uriIntent = getIntent().getData();

		if (FRIEND_PICKER.equals(uriIntent)) {
			if (savedInstance == null) {
				friendPickerFragment = new FriendPickerFragment(bundleArgs);
			} else {
				friendPickerFragment = (FriendPickerFragment) fragmentManager
						.findFragmentById(R.id.frameLayoutPickerFragment);
			}
			friendPickerFragment.setOnErrorListener(this);
			friendPickerFragment.setOnDoneButtonClickedListener(this);
			fragmentToShow = friendPickerFragment;
		} else if (PLACE_PICKER.equals(uriIntent)) {
			if (savedInstance == null) {
				placePickerFragment = new PlacePickerFragment(bundleArgs);
			} else {
				placePickerFragment = (PlacePickerFragment) fragmentManager
						.findFragmentById(R.id.frameLayoutPickerFragment);
			}
			placePickerFragment
					.setOnSelectionChangedListener(new PickerFragment.OnSelectionChangedListener() {

						@Override
						public void onSelectionChanged(
								PickerFragment<?> fragment) {
							// TODO Auto-generated method stub
							finishActivity();
						}
					});
			placePickerFragment
					.setOnErrorListener(new PickerFragment.OnErrorListener() {

						@Override
						public void onError(PickerFragment<?> fragment,
								FacebookException error) {
							// TODO Auto-generated method stub
							PickerActivity.this.onError(error);
						}
					});
			placePickerFragment
					.setOnDoneButtonClickedListener(new PickerFragment.OnDoneButtonClickedListener() {

						@Override
						public void onDoneButtonClicked(
								PickerFragment<?> fragment) {
							// TODO Auto-generated method stub
							finishActivity();
						}
					});
			fragmentToShow = placePickerFragment;
		} else {
			setResult(RESULT_CANCELED);
			finish();
			return;
		}
		fragmentManager.beginTransaction()
				.replace(R.id.frameLayoutPickerFragment, fragmentToShow)
				.commit();
	}

	private void onError(Exception error) {
		onError(error.getLocalizedMessage(), false);
	}

	private void onError(String error, final boolean finishActivity) {
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
		alertDialogBuilder
				.setTitle(R.string.error_dialog_title)
				.setMessage(error)
				.setPositiveButton(R.string.error_dialog_title,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								if (finishActivity) {
									finishActivity();
								}
							}

						});
		alertDialogBuilder.show();
	}

	@Override
	public void onError(PickerFragment<?> fragment, FacebookException error) {
		// TODO Auto-generated method stub
		// PickerActivity.this.onError(fragment, error);
		PickerActivity.this.onError(error);
	}

	@Override
	public void onDoneButtonClicked(PickerFragment<?> fragment) {
		// TODO Auto-generated method stub
		finishActivity();
	}

	private void finishActivity() {
		ScrumptiousApplication scrumptiousApplication = (ScrumptiousApplication) getApplication();
		if (FRIEND_PICKER.equals(getIntent().getData())) {
			if (friendPickerFragment != null) {
				scrumptiousApplication.setSelectedUsers(friendPickerFragment
						.getSelection());
			}
		} 
		else if (PLACE_PICKER.equals(getIntent().getData())) {
			if (placePickerFragment != null) {
				scrumptiousApplication.setSelectedPlace(placePickerFragment
						.getSelection());
			}
		}
		setResult(RESULT_OK, null);
		finish();
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		if (FRIEND_PICKER.equals(getIntent().getData())) {
			try {
				friendPickerFragment.loadData(false);
			} catch (Exception e) {
				onError(e);
			}
		} else if (PLACE_PICKER.equals(getIntent().getData())) {
			try {
				Location location = null;
				Criteria criteria = new Criteria();
				LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
				String strBestProvider = locationManager.getBestProvider(
						criteria, false);
				if (strBestProvider != null) {
					location = locationManager
							.getLastKnownLocation(strBestProvider);
					if (locationManager.isProviderEnabled(strBestProvider)
							&& locationListener == null) {
						locationListener = new LocationListener() {
							@Override
							public void onStatusChanged(String provider,
									int status, Bundle extras) {
								// TODO Auto-generated method stub

							}

							@Override
							public void onProviderEnabled(String provider) {
								// TODO Auto-generated method stub

							}

							@Override
							public void onProviderDisabled(String provider) {
								// TODO Auto-generated method stub

							}

							@Override
							public void onLocationChanged(Location location) {
								// TODO Auto-generated method stub
								float fltDistance = location
										.distanceTo(placePickerFragment
												.getLocation());
								if (fltDistance >= LOCATION_CHANGE_THRESHOLD) {
									placePickerFragment.setLocation(location);
									placePickerFragment.loadData(true);
								}
							}
						};
						locationManager.requestLocationUpdates(strBestProvider,
								1, LOCATION_CHANGE_THRESHOLD, locationListener,
								Looper.getMainLooper());
					}
				}
				if (location == null) {
					String strModel = Build.MODEL;
					if (strModel.equals("sdk") || strModel.equals("google_sdk")
							|| strModel.contains("x86")) {
						location = LOCATION_HERZLIYA;
					}
				}
				if (location != null) {
					placePickerFragment.setLocation(location);
					placePickerFragment.setRadiusInMeters(SEARCH_RADIUS_METERS);
					placePickerFragment.setSearchText(SEARCH_TEXT);
					placePickerFragment.setResultsLimit(SEARCH_RESULTS_LIMIT);
					placePickerFragment.loadData(true);
				} else {
					onError(getResources()
							.getString(R.string.no_location_error), true);
				}
			} catch (Exception e) {
				onError(e);
			}
		}
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		if (locationListener != null) {
			LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
			locationManager.removeUpdates(locationListener);
			locationListener = null;
		}
	}
}
